package com.hotacorp.opencloud.common.resourcecommon.exception;

import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.hotacorp.opencloud.common.commdata.Result;

/**
 * rest控制器出错后的处理切面，覆盖确实的处理
 * @author lwg
 *
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

	@ExceptionHandler({ IllegalArgumentException.class })
	@ResponseStatus(HttpStatus.OK)
	public Result<?> badRequestException(IllegalArgumentException exception) {
		return new Result<>(null, HttpStatus.BAD_REQUEST.value(), exception.getMessage());
	}

	@ExceptionHandler({ AccessDeniedException.class })
	@ResponseStatus(HttpStatus.OK)
	public Result<?> badMethodExpressException(AccessDeniedException exception) {
		return new Result<>(null, HttpStatus.FORBIDDEN.value(), exception.getMessage());
	}
	@ExceptionHandler({ OpenCloudException.class })
	@ResponseStatus(HttpStatus.OK)
	public Result<?> openCloudException(OpenCloudException exception) {
		return new Result<>(null, exception.getCode(), exception.getMessage());
	}
	@ExceptionHandler({ MethodArgumentNotValidException.class })
	@ResponseStatus(HttpStatus.OK)
	public Result<?> argNotValid(MethodArgumentNotValidException exception) {
		BindingResult bindingResult = exception.getBindingResult();
		StringBuilder msg = new StringBuilder();
		for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
			FieldError fieldError = bindingResult.getFieldErrors().get(i);
			msg.append(fieldError.getDefaultMessage()).append("<br>");
		}
		
		return new Result<>(null, HttpStatus.BAD_REQUEST.value(), msg.toString());
	}

	@ExceptionHandler(Throwable.class)
	@ResponseStatus(HttpStatus.OK)
	public Result<?> handleError(Throwable e) {
		return new Result<>(null, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
	}
}
